<template>
  <div>
      <van-nav-bar :title="$route.name" @click-left="$router.back()" left-arrow/>
      <!-- 有数据 -->
    <div v-if="cartlist.length > 0">
      <van-swipe-cell v-for="item in cartlist" :key="item.id">
        <van-card
          :num="item.num"
          :price="item.price | toPrice"
          desc="描述信息"
          :title="item.goodsname"
          class="goods-card"
          :thumb="item.img"
        >
          <template #footer>
            <van-stepper v-model="item.num" theme="round" button-size="22" disable-input/>
          </template>
        </van-card>
        <template #right>
          <van-button
            @click="del(item.id)"
            square
            text="删除"
            type="danger"
            class="delete-button btnInfo"
          />
        </template>
      </van-swipe-cell>
    </div>
    <!-- 无数据状态 -->
    <div v-else>
      <van-empty description="购物车空空如也，快去买买买！！！"/>
    </div>
  </div>
</template>

<script>
import { cartList, deleteCart } from "../request/api";
import { Toast } from "vant";
export default {
  data() {
    return {
        cartlist:[]
    };
  },
  beforeRouteEnter(to, from, next) {
    if (sessionStorage.getItem("userinfo")) {
      next();
    } else {
      //无登录状态，强制调转到登录页
      next("/login");
    }
  },
   mounted() {
    //组件一加载就调用 购物车列表接口
    cartList({
      uid: this.$store.getters.getUser.uid
    }).then(res => {
      console.log(res, "购物车列表");
      if (res.code == 200) {
        this.cartlist = res.list ? res.list : [];
      }
    });
  },
  methods: {
    //删除
    del(id) {
      deleteCart({ id }).then(res => {
        if (res.code == 200) {
          Toast.success(res.msg);
          location.reload();
        } else {
          Toast.fail(res.msg);
        }
      });
    }
  }
};
</script>

<style scoped>
.btnInfo {
  height: 100%;
}
.van-nav-bar{
  background: red;
  height: 50px;
  margin-bottom: 10px;
}
</style>
